package com.zhousb.deviceManager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhousb.deviceManager.exception.CustomerException;
import com.zhousb.deviceManager.mapper.KiAssetEpcRelationMapper;
import com.zhousb.deviceManager.model.entity.KiAssetEpcRelation;
import com.zhousb.deviceManager.model.so.AssetEpcRelationSo;
import com.zhousb.deviceManager.service.AssetEpcRelationService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author zhousb
 * @date 2024/11/19 4:51
 * @description
 */
@Service
public class AssetEpcRelationServiceImpl implements AssetEpcRelationService {
    @Resource
    private KiAssetEpcRelationMapper kiAssetEpcRealtionMapper;

    @Override
    public IPage page(Page page, AssetEpcRelationSo so) {
        LambdaQueryWrapper<KiAssetEpcRelation> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.hasText(so.getKeyword())){
            queryWrapper.like(KiAssetEpcRelation::getAssetCode, so.getKeyword()).or().like(KiAssetEpcRelation::getEpc,so.getKeyword());
        }
        return kiAssetEpcRealtionMapper.selectPage(page,queryWrapper);
    }

    @Override
    public boolean importExcel(MultipartFile file)  {
        try {
            List<KiAssetEpcRelation> rawList = EasyExcel.read(file.getInputStream())
                    .head(KiAssetEpcRelation.class)
                    .sheet()
                    .doReadSync();
            int limit = (rawList.size() + 200 - 1) / 200;
            List<List<KiAssetEpcRelation>> splitList = Stream.iterate(0, n -> n + 1).limit(limit).parallel()
                    .map(a -> rawList.stream().skip((long) a * 200).limit(200).parallel()
                            .collect(Collectors.toList()))
                    .toList();
            for (List<KiAssetEpcRelation> list : splitList) {
                kiAssetEpcRealtionMapper.batchInsert(list);
            }
            return false;
        } catch (IOException e) {
            throw new CustomerException("导入失败");
        }


    }

    @Override
    public boolean delete(String code) {
        kiAssetEpcRealtionMapper.remove(code);
        return true;
    }
}
